package com.yijumao.shop.service.impl;

import com.yijumao.shop.domain.Item;
import com.yijumao.shop.domain.OrderItem;
import com.yijumao.shop.domain.Orders;
import com.yijumao.shop.mapper.OrderItemMapper;
import com.yijumao.shop.mapper.OrdersMapper;
import com.yijumao.shop.service.ItemService;
import com.yijumao.shop.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.dc.pr.PRError;

import java.util.List;

/**
 * @author konley
 * @date 2020-11-15 15:51
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ItemService itemService;

    @Override
    public int deleteByPrimaryKey(String oid) {
        return ordersMapper.deleteByPrimaryKey(oid);
    }

    @Override
    public int insert(Orders record) {
        return ordersMapper.insert(record);
    }

    @Override
    public Orders selectByPrimaryKey(String oid) {
        return ordersMapper.selectByPrimaryKey(oid);
    }

    @Override
    public List<Orders> selectAll() {
        return ordersMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(Orders record) {
        return ordersMapper.updateByPrimaryKey(record);
    }

    @Override
    public void creatOrder(Orders orders) {
        //添加订单
        ordersMapper.insert(orders);
        //添加订单项
        for (OrderItem orderItem : orders.getOrderItems()) {
            orderItemMapper.insert(orderItem);
        }
    }

    @Override
    public List<Orders> selectByUid(Integer uid) {
        //获取到订单信息
        List<Orders> orders = ordersMapper.selectByUid(uid);
        //向订单集合添加订单
        for (Orders order : orders) {
            //向订单对象添加订单项
            String oid = order.getOid();
            //根据当前订单对象的oid找到所有订单项
            List<OrderItem> items = orderItemMapper.selectByOid(oid);
            //向当前订单项中添加订单
            for (OrderItem item : items) {
                Item add = itemService.selectByPrimaryKey(item.getId());
                item.setItem(add);
            }
            //向订单对象的订单项集合里添加当前订单项
            order.setOrderItems(items);
        }
        return orders;
    }
}
